package sz.szsmk.citizencard.mvp.presenter;

import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.youzan.spiderman.utils.MD5Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.HandlerPoster;

import javax.inject.Inject;

import rx.functions.Action1;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.bean.request.AccessTokenRequest;
import sz.szsmk.citizencard.model.network.bean.request.GetOrderOpenid;
import sz.szsmk.citizencard.model.network.bean.request.GetTokenReq;
import sz.szsmk.citizencard.model.network.bean.request.HomeWeathReq;
import sz.szsmk.citizencard.model.network.bean.request.IBaseRequest;
import sz.szsmk.citizencard.model.network.bean.request.QueryCitizenCardReq;
import sz.szsmk.citizencard.model.network.bean.request.QueryPageAdRequest;
import sz.szsmk.citizencard.model.network.bean.request.QueryPageResourceReq;
import sz.szsmk.citizencard.model.network.bean.request.QueryUserCardRequest;
import sz.szsmk.citizencard.model.network.bean.request.RecordUserFuncRequest;
import sz.szsmk.citizencard.model.network.bean.request.UserBehaviorBrowseReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CloudFlashRes;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.GetTokenRes;
import sz.szsmk.citizencard.model.network.bean.response.GetUrlRes;
import sz.szsmk.citizencard.model.network.bean.response.HomeAllfunResponse;
import sz.szsmk.citizencard.model.network.bean.response.HomeHeadFuncResponse;
import sz.szsmk.citizencard.model.network.bean.response.HomeWeathRes;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.model.network.bean.response.IbaseBean;
import sz.szsmk.citizencard.model.network.bean.response.OneWordRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryCitizenCardRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryMainAdRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryPageAdresponse;
import sz.szsmk.citizencard.model.network.bean.response.QueryPageResourceRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserCardResponse;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.SplashResponse;
import sz.szsmk.citizencard.mvp.contract.IHomeContact;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.IObjectSignatureUtil;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/4 19:58
 * description:
 */
public class HomePresenter extends IBasePresenter
        implements IHomeContact.IHomePresenter<IHomeContact.IHomeView> {
    private NetworkDateSources mNetworkDateSource;
    private NetworkDateSources mNetworkDate;

    GsdxNetApi gsdxNetApi;

    @Inject
    public HomePresenter(GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;
        this.mNetworkDate = NetworkDateSources.getInstance();
        this.mNetworkDateSource = NetworkDateSources.getInstance();
    }

    @Override
    public void getUserInfo() {

        IBaseRequest userInfoReq = new IBaseRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        userInfoReq.setAccess_token(access_token);
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        userInfoReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
        String key = "access_token=" + access_token + "&device_id=" + androidId + "&key=" + refresh_token;
        String stringMd5 = MD5Utils.getStringMd5(key).toUpperCase();
        userInfoReq.setSign(stringMd5);
        String json = new Gson().toJson(userInfoReq);
        L.e(Constant.TAG, "getUserInfoZhsz:" + json);
        mNetworkDateSource.getUserInfoZhsz(userInfoReq, new SubscribeResult<IUserInfo>() {
            @Override
            protected void onOk(IUserInfo response) {
                String mobile = response.getUserEx().getMobile();
                ACache.get(DaggerApplication.getIns()).remove("mobile");
                ACache.get(DaggerApplication.getIns()).put("mobile", mobile);
                ACache.get(DaggerApplication.getIns()).put("userId", response.getUserEx().getId() + "");
                String json = new Gson().toJson(response);
                ACache.get(DaggerApplication.getIns()).put("userinfo", json);
                ((IHomeContact.IHomeView) mView).getUserInfoSucc(response);

            }

            @Override
            protected void onNext(IUserInfo response) {
                super.onNext(response);
                ((IHomeContact.IHomeView) mView).getUserInfoFail(response);
            }

            @Override
            protected void onFailure(IUserInfo response) {
                super.onFailure(response);
                ((IHomeContact.IHomeView) mView).getUserInfoFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryHeadFunc() {
        IBaseRequest baseRequest = IObjectSignatureUtil.getBaseRequest();
        String json = new Gson().toJson(baseRequest);
        L.e(Constant.TAG, json);
        mNetworkDateSource.queryHeadFunc(baseRequest, new SubscribeResult<HomeHeadFuncResponse>() {
            @Override
            protected void onOk(HomeHeadFuncResponse response) {
                if (response == null) {
                    return;
                }
                String json = new Gson().toJson(response);
//                L.e(Constant.TAG, "queryHeadFunc响应:" + json);
                HomeHeadFuncResponse homeHeadFuncResponse = new Gson().fromJson(json, HomeHeadFuncResponse.class);
                ((IHomeContact.IHomeView) mView).queryHeadFuncSucc(homeHeadFuncResponse);
            }

            @Override
            protected void onFailure(HomeHeadFuncResponse response) {
                super.onFailure(response);
                ((IHomeContact.IHomeView) mView).updataError(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryAllFunc() {
        IBaseRequest baseRequest = IObjectSignatureUtil.getBaseRequest();
        String json = new Gson().toJson(baseRequest);
        L.e(Constant.TAG, "queryAllFunc" + json);
        mNetworkDateSource.queryAllFunc(baseRequest, new SubscribeResult<HomeAllfunResponse>() {
            @Override
            protected void onOk(HomeAllfunResponse response) {
                if (response == null) {
                    return;
                }
                String json = new Gson().toJson(response);
//                L.e(Constant.TAG, "queryAllFunc响应:" + json);

                ((IHomeContact.IHomeView) mView).queryAllFuncSucc(response);
            }

            @Override
            protected void onFailure(HomeAllfunResponse response) {
                super.onFailure(response);
                ((IHomeContact.IHomeView) mView).updataError(response);

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryMainAd() {
        IBaseRequest baseRequest = IObjectSignatureUtil.getBaseRequest();
        String json = new Gson().toJson(baseRequest);
        L.e(Constant.TAG, "queryMainAd:" + json);
        mNetworkDateSource.queryMainAd(baseRequest, new SubscribeResult<QueryMainAdRes>() {
            @Override
            protected void onOk(QueryMainAdRes response) {
                if (response == null) {
                    return;
                }
                String json = new Gson().toJson(response);
//                L.e(Constant.TAG, "queryMainAd响应:" + json);
                SplashResponse splashResponse = new Gson().fromJson(json, SplashResponse.class);
                ((IHomeContact.IHomeView) mView).queryMainAdSucc(splashResponse);
            }

            @Override
            protected void onFailure(QueryMainAdRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryPageAd() {
        QueryPageAdRequest queryPageAdRequest = new QueryPageAdRequest();
        queryPageAdRequest.setResource_page_id(1);
        queryPageAdRequest.setAccess_token("5463d411b93f80c5f9e169d718b65025");
        queryPageAdRequest.setSign("8AD4BE2948A48DE06E487FFB0619449E");

        String json = new Gson().toJson(queryPageAdRequest);
        L.e(Constant.TAG, "queryPageAd:" + json);
        mNetworkDateSource.queryPageAd(queryPageAdRequest, new SubscribeResult<IbaseBean>() {
            @Override
            protected void onOk(IbaseBean response) {
                if (response == null) {
                    return;
                }
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "queryPageAd响应:" + json);
                QueryPageAdresponse queryPageAdresponse = new Gson().fromJson(json, QueryPageAdresponse.class);
                ((IHomeContact.IHomeView) mView).queryPageAdSucc(queryPageAdresponse);
            }

            @Override
            protected void onFailure(IbaseBean response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void recordUserFunc() {
        RecordUserFuncRequest recordUserFuncRequest = new RecordUserFuncRequest();
        recordUserFuncRequest.setSign("8AD4BE2948A48DE06E487FFB0619449E");
        recordUserFuncRequest.setAccess_token("5463d411b93f80c5f9e169d718b65025");
        recordUserFuncRequest.setFunction_id(1);
        mNetworkDateSource.recordUserFunc(recordUserFuncRequest, new SubscribeResult<IbaseBean>() {
            @Override
            protected void onOk(IbaseBean response) {
                if (response == null) {
                    return;
                }
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "recordUserFunc响应:" + json);
            }

            @Override
            protected void onFailure(IbaseBean response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryPageResource(final int area_id) {
        QueryPageResourceReq pageResourceReq = new QueryPageResourceReq();
//        pageResourceReq.setResource_area_id(area_id);
        pageResourceReq.setResource_area_id(area_id);
        pageResourceReq.setAccess_token("string");
        pageResourceReq.setDevice_id("string");
        pageResourceReq.setSign("string");
        String json = new Gson().toJson(pageResourceReq);
        L.e(Constant.PATH, "pageResourceReq----->" + json);
        mNetworkDateSource.queryPageResource(pageResourceReq, new SubscribeResult<QueryPageResourceRes>() {
            @Override
            protected void onOk(QueryPageResourceRes response) {
                String toJson = new Gson().toJson(response);
//                L.e(Constant.PATH, "QueryPageResourceRes----->" + area_id + "=====" + toJson);
                if (response != null) {
                    ((IHomeContact.IHomeView) mView).queryPageResourceSucc(response, area_id);
                }
            }


            @Override
            protected void onFailure(QueryPageResourceRes response) {
                super.onFailure(response);
                String toJson = new Gson().toJson(response);

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryUserCard() {
        QueryUserCardRequest cardRequest = new QueryUserCardRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        cardRequest.setAccess_token(access_token);
        cardRequest.setType("00");
        String json = new Gson().toJson(cardRequest);

        mNetworkDate.queryUserCardInfo(cardRequest, new SubscribeResult<QueryUserCardRes>() {
            @Override
            protected void onOk(QueryUserCardRes response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "queryUserCard----->" + json);
//                ((IHomeContact.IHomeView) mView).queryUserCardSucc(response);
            }

            @Override
            protected void onFailure(QueryUserCardRes response) {
                super.onFailure(response);
                ((IHomeContact.IHomeView) mView).queryUserCardFail(response.getMessage());
            }

            @Override
            protected void onNext(QueryUserCardRes response) {
                super.onNext(response);
                ((IHomeContact.IHomeView) mView).queryUserCardFail(response.getMessage());
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    @Override
    public void queryOneWordAd() {
        IBaseRequest iBaseRequest = new IBaseRequest();
        iBaseRequest.setDevice_id("string");
        iBaseRequest.setSign("string");
        mNetworkDateSource.queryOneWordAd(iBaseRequest, new SubscribeResult<OneWordRes>() {

            @Override
            protected void onOk(OneWordRes response) {
                ((IHomeContact.IHomeView) mView).queryOneWordAdSucc(response);
            }

            @Override
            protected void onFailure(OneWordRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void getToken(String refresh_token) {
        GetTokenReq getTokenReq = new GetTokenReq();
        getTokenReq.setRefresh_token(refresh_token);
        getTokenReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        getTokenReq.setToken_type("1");
        mNetworkDateSource.getToken(getTokenReq, new SubscribeResult<GetTokenRes>() {
            @Override
            protected void onOk(GetTokenRes response) {
                String access_token = response.getAccess_token();
                ACache.get(DaggerApplication.getIns()).put("access_token", access_token);
                ((IHomeContact.IHomeView) mView).getTokenSucc();
            }

            @Override
            protected void onNext(GetTokenRes response) {
                super.onNext(response);
            }

            @Override
            protected void onFailure(GetTokenRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });

    }

    @Override
    public void checkSuccessOrderStatus(String access_token) {
        OkHttpUtils.post()
                .url(Constant.BASE_URL + "app/supply/CheckSuccessOrderStatusReq")
                .addParams("access_token", access_token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        CloudFlashRes cloudFlashRes = new Gson().fromJson(response, CloudFlashRes.class);
                        if (cloudFlashRes != null) {
                            if (mView != null) {
                                String code = cloudFlashRes.getCode();
                                if (code.equals("000000")) {
                                    String orderStatus = cloudFlashRes.getOrderStatus();
                                    if (orderStatus != null) {
                                        ACache.get(DaggerApplication.getIns()).put("orderStatus", orderStatus);
                                    }
                                    ACache.get(DaggerApplication.getIns()).put("orderStatus", orderStatus);
                                    ((IHomeContact.IHomeView) mView).checkSuccessOrderStatusSucc(orderStatus);
                                } else {
                                    ((IHomeContact.IHomeView) mView).checkSuccessOrderStatusFail(cloudFlashRes);
                                }
                            }

                        }
                    }
                });
    }

    @Override
    public void getWeathGeneral() {
        HomeWeathReq homeWeathReq = new HomeWeathReq();
        homeWeathReq.setCityName("苏州");
        homeWeathReq.setUserId(ACache.get(DaggerApplication.getIns()).getAsString("userId"));
        mNetworkDateSource.getWeathGeneral(homeWeathReq, new SubscribeResult<HomeWeathRes>() {
            @Override
            protected void onOk(HomeWeathRes response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "getWeathGeneral:" + json);
                ((IHomeContact.IHomeView) mView).getWeathGeneralSucc(response);
            }

            @Override
            protected void onFailure(HomeWeathRes response) {
                super.onFailure(response);

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void getGetOrderId(final String type, final String url) {
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        GetOrderOpenid getOrderOpenid = new GetOrderOpenid();
        getOrderOpenid.setAccess_token(access_token);
        getOrderOpenid.setTag("HUIMIN");
        String json = new Gson().toJson(getOrderOpenid);
        L.e(Constant.TAG, "getOrderOpenid----->" + json);
        mNetworkDateSource.getOrderOpenid(getOrderOpenid, new SubscribeResult<GetOrderOpenidRes>() {
            @Override
            protected void onOk(GetOrderOpenidRes response) {
                String toJson = new Gson().toJson(response);
                Constant.EXTENT = response.getExtend();
                ((IHomeContact.IHomeView) mView).getGetOrderIdSucc(response, type, url);
            }

            @Override
            protected void onNext(GetOrderOpenidRes response) {
                super.onNext(response);
                String toJson = new Gson().toJson(response);
                L.e(Constant.TAG, "-------------" + toJson);
            }

            @Override
            protected void onFailure(GetOrderOpenidRes response) {
                super.onFailure(response);
                String toJson = new Gson().toJson(response);
                if (response.getCode().equals("0000")) {
                    ACache.get(DaggerApplication.getIns()).remove("mextend");
                    ACache.get(DaggerApplication.getIns()).put("mextend", response.getExtend());
                }
                L.e(Constant.TAG, "-------------" + toJson);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    @Override
    public void getUrl() {
        AccessTokenRequest tokenRequest = new AccessTokenRequest();
        mNetworkDateSource.getUrl(tokenRequest, new SubscribeResult<GetUrlRes>() {
            @Override
            protected void onOk(GetUrlRes response) {
                ((IHomeContact.IHomeView) mView).getUrlSucc(response);
            }

            @Override
            protected void onFailure(GetUrlRes response) {
                super.onFailure(response);
                ((IHomeContact.IHomeView) mView).getUrlFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void selectUserAuth(final String type) {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        mNetworkDateSource.selectUserAuth(accessTokenRequest, new SubscribeResult<SeleciUserAuthRes>() {
            @Override
            protected void onOk(SeleciUserAuthRes response) {
                ((IHomeContact.IHomeView) mView).selectUserAuthSucc(response, type);
            }

            @Override
            protected void onFailure(SeleciUserAuthRes response) {
                super.onFailure(response);
                Toast.makeText(DaggerApplication.getIns(), response.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryCitizenCard() {
        QueryCitizenCardReq queryCitizenCardReq = new QueryCitizenCardReq();
        queryCitizenCardReq.setType("0");
        String json = new Gson().toJson(queryCitizenCardReq);
        mNetworkDateSource.queryCitizenCard(queryCitizenCardReq, new SubscribeResult<QueryCitizenCardRes>() {
            @Override
            protected void onOk(QueryCitizenCardRes response) {
                String json = new Gson().toJson(response);
                ((IHomeContact.IHomeView) mView).queryCitizenCardSucc(response);
            }

            @Override
            protected void onFailure(QueryCitizenCardRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void userBehaviorBrowse(int id) {
        UserBehaviorBrowseReq userBehaviorBrowseReq = new UserBehaviorBrowseReq();
        if(id==-1){
            return;
        }
        userBehaviorBrowseReq.setModularId(id);
        userBehaviorBrowseReq.setAccessToken(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));

        mNetworkDateSource.userBehaviorBrowse(userBehaviorBrowseReq, new Action1<BaseBean>() {
            @Override
            public void call(BaseBean baseBean) {

                L.e(Constant.TAG, "ok----->" );
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

}
